package com.simen.hellobytes.runtime;

import com.simen.hellobytes.IOUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

class StreamInfoReader extends Thread {
    private final InputStream inputStream;
    private BufferedReader bufferedReader;
    private boolean exception = false;
    private StringBuilder buffer;
    private boolean closeStreamAfterRead = false;

    public StreamInfoReader(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    @Override
    public void run() {
        bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        buffer = new StringBuilder();
        String line = null;

        try {
            while ((line = bufferedReader.readLine()) != null) {
                buffer.append(line).append("\n");
            }
        } catch (IOException e) {
            exception = true;
        } finally {
            if (closeStreamAfterRead) IOUtil.closeSilently(bufferedReader);
        }
    }

    public StreamInfoReader read() {
        run();
        return this;
    }

    public String result() {
        return exception ? "" : buffer.toString();
    }

    public StreamInfoReader setCloseStreamAfterRead(boolean closeStreamAfterRead) {
        this.closeStreamAfterRead = closeStreamAfterRead;
        return this;
    }

    public boolean isCloseStreamAfterRead() {
        return closeStreamAfterRead;
    }
}
